# coding: utf-8

import time
import requests
import xlsxwriter

URL = 'http://web.meishuquan.net/rest/user/get-user?user_id={}'


def run():
    user_ids = range(1, 5)
    get_users(user_ids)


def get_users(user_ids):
    print 'get_users'
    filename = 'user_{}to{}.xlsx'.format(user_ids[0], user_ids[-1])
    path = '/tmp/{}'.format(filename)
    wb = xlsxwriter.Workbook(path)
    sheet = wb.add_worksheet('sheet 1')

    for index, user_id in enumerate(user_ids):
        try:
            user_data = get_user(user_id)
            if user_data:
                if index == 0:
                    sheet.write_row(0, 0, user_data.iterkeys())
                sheet.write_row(index + 1, 0, user_data.itervalues())
            time.sleep(1)
        except:
            pass
    wb.close()


def get_user(user_id):
    print 'get_user', user_id
    url = URL.format(user_id)
    r = requests.get(url)
    d = r.json()
    print d
    if d['option']['status'] == 0:
        return d['data']
    return False


if __name__ == '__main__':
    run()
